<script setup lang="ts">
import { mdRoutes } from '@/router'
import { generateSidebar } from '@/utils/SideBarUtil'
import { useRoute, useRouter } from 'vue-router'
import { computed, ref, watch } from 'vue'
const route = useRoute()
const router = useRouter()

// 存储各页面下标题的折叠状态，格式为 { 页面路径: { 标题: 折叠状态 } }
const collapsedState = ref<Record<string, Record<string, boolean>>>({})

// 获取当前页面的基础路径（如 /docs/创意艺术/）
const getCurrentPageBasePath = (path: string) => {
  const pathSegs = path.split('/').filter(Boolean)
  // 如果是docs下的二级路径，返回前两段组成的路径
  if (pathSegs[0] === 'docs' && pathSegs.length >= 2) {
    return `/${pathSegs[0]}/${pathSegs[1]}/`
  }
  return path
}

// 检查当前路径是否属于某个父项的子项
const isChildOfParent = (
  currentPath: string,
  parentItem: { path: string; children?: Array<{ path: string }> },
) => {
  if (!parentItem.children || parentItem.children.length === 0) {
    return false
  }

  // 检查当前路径是否精确匹配任何一个子项
  const isDirectChild = parentItem.children.some((child) => child.path === currentPath)

  if (isDirectChild) {
    return true
  }

  // 检查当前路径是否以父项路径开头（用于处理index.md等情况）
  const parentPath = parentItem.path.endsWith('/') ? parentItem.path : parentItem.path + '/'
  return currentPath.startsWith(parentPath)
}

// 初始化折叠状态
const initializeCollapsedState = () => {
  const currentPageBasePath = getCurrentPageBasePath(route.path)

  // 如果当前页面还没有折叠状态记录，则初始化
  if (!collapsedState.value[currentPageBasePath]) {
    collapsedState.value[currentPageBasePath] = {}

    const items = generateSidebar(mdRoutes, route.path)

    // 初始化所有标题的折叠状态
    items.forEach((item) => {
      if (item.children && item.children.length > 0) {
        // 默认所有项都是折叠状态
        collapsedState.value[currentPageBasePath][item.title] = true
      }
    })
  }
}

// 根据当前路径动态生成侧边栏内容
const sidebarItems = computed(() => generateSidebar(mdRoutes, route.path))

// 检查父项是否应该处于活动状态（当前路径是父项本身或其子项）
const isParentActive = (path: string) => {
  // 如果当前路径精确匹配父项路径，则显示选中效果
  if (route.path === path) {
    return true
  }

  // 查找对应的侧边栏项
  const parentItem = sidebarItems.value.find((item) => item.path === path)
  if (!parentItem) {
    return false
  }

  // 如果当前路径是该父项的子项，则父项也显示选中效果
  return isChildOfParent(route.path, parentItem)
}

// 检查子项是否应该处于活动状态
const isActive = (path: string) => {
  // 精确匹配当前路径
  return route.path === path
}

// 切换折叠状态
const toggleCollapse = (title: string) => {
  const currentPageBasePath = getCurrentPageBasePath(route.path)

  // 只切换当前项的折叠状态，不影响其他项
  collapsedState.value[currentPageBasePath][title] =
    !collapsedState.value[currentPageBasePath][title]
}

// 监听路由变化，当切换到不同页面时初始化折叠状态
watch(
  () => route.path,
  (newPath, oldPath) => {
    const newPageBasePath = getCurrentPageBasePath(newPath)
    const oldPageBasePath = oldPath ? getCurrentPageBasePath(oldPath) : ''

    // 如果切换到不同的页面，则初始化新页面的折叠状态
    if (newPageBasePath !== oldPageBasePath) {
      initializeCollapsedState()
    }

    // 检查是否在折叠状态下进入第一个子项
    const currentPageBasePath = getCurrentPageBasePath(newPath)
    if (collapsedState.value[currentPageBasePath]) {
      sidebarItems.value.forEach((item) => {
        if (item.children && item.children.length > 0) {
          // 检查当前路径是否是该父项的第一个子项
          const firstChildPath = item.children[0]?.path
          if (newPath === firstChildPath && collapsedState.value[currentPageBasePath][item.title]) {
            // 如果是第一个子项且当前是折叠状态，则展开
            collapsedState.value[currentPageBasePath][item.title] = false
          }
        }
      })
    }
  },
  { immediate: true },
)

// 检查是否处于折叠状态
const isCollapsed = (title: string) => {
  const currentPageBasePath = getCurrentPageBasePath(route.path)
  return collapsedState.value[currentPageBasePath]?.[title] !== false // 默认为折叠状态
}

const navigateTo = (path: string) => {
  // 使用 try-catch 包装导航调用，以处理可能的导航错误
  try {
    // 检查是否是当前路径，避免不必要的导航
    if (route.path !== path) {
      router
        .push(path)
        .then(() => {
          // 导航成功后，触发事件关闭侧边栏
          emit('close-drawer')
        })
        .catch((err) => {
          // 如果导航失败，可能是由于重复导航或其他原因
          console.error('Navigation failed:', err)
        })
    } else {
      // 如果是当前路径，直接关闭侧边栏
      emit('close-drawer')
    }
  } catch (error) {
    console.error('Navigation error:', error)
  }
}

// 定义 emit 事件
const emit = defineEmits(['close-drawer'])
</script>

<template>
  <aside class="whole-aside">
    <div v-for="item in sidebarItems" :key="item.path" class="sidebar-Items">
      <div
        @click="navigateTo(item.path)"
        class="items-title"
        :class="{
          active: isParentActive(item.path),
          collapsible: item.children && item.children.length > 0,
        }"
      >
        {{ item.title }}
        <div
          v-if="item.children && item.children.length > 0"
          class="collapse-button"
          @click.stop="toggleCollapse(item.title)"
        >
          <span class="collapse-icon">
            {{ isCollapsed(item.title) ? '▶' : '▼' }}
          </span>
        </div>
      </div>
      <transition name="slide">
        <div v-if="item.children && !isCollapsed(item.title)" class="children-container">
          <div v-for="child in item.children" :key="child.path">
            <div
              @click="navigateTo(child.path)"
              class="items-children"
              :class="{ active: isActive(child.path) }"
            >
              {{ child.title }}
            </div>
          </div>
        </div>
      </transition>
    </div>
  </aside>
</template>

<style scoped>
.whole-aside {
  padding-left: 0;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  width: 260px;
  max-width: 80vw;
  height: 100%;
  overflow-y: auto;
  position: relative;
  /* 隐藏滚动条但保持滚动功能 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

/* 隐藏滚动条 - Webkit浏览器 (Chrome, Safari) */
.whole-aside::-webkit-scrollbar {
  display: none;
}
.sidebar-Items {
  display: flex;
  flex-direction: column;
  width: 100%;
  padding-top: 0;
}
.items-title {
  font-family: 'Microsoft YaHei', 'SimHei', sans-serif;
  font-size: 1rem;
  font-weight: 900;
  padding: 8px 10px;
  border-radius: 4px;
  margin-bottom: 8px;
  color: #2c3e50;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.items-title.active {
  color: #3a8ee6;
}
.items-title.collapsible {
  cursor: pointer;
}
.items-title-text {
  transition: color 0.2s ease;
}
.items-title-text:hover {
  color: #3a8ee6;
}
.collapse-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  border-radius: 4px;
  cursor: pointer;
  transition: color 0.2s ease;
}
.collapse-button:hover {
  color: #3a8ee6;
}
.collapse-icon {
  font-size: 0.8rem;
  color: #2c3e50;
  transition: transform 0.3s ease;
}
/* 折叠展开动画 */
.slide-enter-active,
.slide-leave-active {
  transition: all 0.3s ease;
  max-height: 1000px;
  opacity: 1;
  overflow: hidden;
}
.slide-enter-from,
.slide-leave-to {
  max-height: 0;
  opacity: 0;
  margin: 0;
  padding: 0;
}
.children-container {
  margin-left: 15px;
  overflow: hidden;
}
.items-children {
  padding: 6px 10px;
  border-radius: 4px;
  margin-bottom: 8px;
  color: #2c3e50;
  font-weight: 600;
  transition: color 0.2s ease;
  cursor: pointer;
}
.items-children:hover {
  color: #3a8ee6;
}
.items-children.active {
  color: #3a8ee6;
}
</style>
